//用户vuex 数据模块
//解构ajax接口函数
import {checkLoginReq, getUserInfoReq} from '@/api/user'
const state = {
  //初始化 从本地拉取数据赋值给vuex
  token: localStorage.getItem('t_k'), //token
  role: localStorage.getItem('role'), //角色
  userInfo: {}, //用户信息
}
//同步方法 同步修改数据
const mutations = {
  SET_TOKEN(state, data) {
    //token存vuex
    state.token = data
    //token存本地
    localStorage.setItem('t_k', data)
  },
  SET_ROLE(state, data) {
    state.role = data
    localStorage.setItem('role', data)
  },
  SET_USERINFO(state, data) {
    state.userInfo = data
  },
  CLEAR(state) {
    //清空vuex
    state.userInfo = {}
    state.token = ''
    state.role = ''

    //清空本地
    localStorage.clear()
  },
}

//异步方法
const actions = {
  //登录
  A_login({commit}, data) {
    //凡是 actions里面有异步 必须包一层Promise壳子
    return new Promise(async resolve => {
      //发送请求
      let res = await checkLoginReq(data)
      //解构数据
      let {code, token, role} = res.data
      //判断
      if (code === 0) {
        commit('SET_TOKEN', 'Bearer ' + token)
        commit('SET_ROLE', role)

        //切换promise状态为 已成功
        resolve()
      }
    })
  },

  //获取用户信息
  A_getUserInfo({commit}) {
    return new Promise(async (resolve, reject) => {
      // try {
      //   //发送请求
      //   let res = await getUserInfoReq()
      //   //调用mutations里面的同步方法 存储数据到vuex中
      //   commit('SET_USERINFO', res.data)
      //   resolve()
      // } catch (error) {
      //   reject(error)
      // }

      getUserInfoReq()
        .then(res => {
          commit('SET_USERINFO', res.data)
          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  },

  //清空数据
  A_clear({commit}) {
    return new Promise(resolve => {
      commit('CLEAR')
      resolve()
    })
  },
}

export default {
  //命名空间
  namespaced: true,
  state,
  mutations,
  actions,
}
